package io.github.betwowt.minio.web;

import io.github.betwowt.minio.common.Response;
import io.github.betwowt.minio.util.FileUtil;
import io.minio.MinioClient;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author betwowt
 * @date 2019/04/01
 */
@RestController
@RequestMapping("/file")
public class FileResource {

    @Autowired
    private MinioClient minioClient;

    @PostMapping("/upload")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", paramType = "form", dataType = "__file", required = true, value = "上传文件"),
            @ApiImplicitParam(name = "bucketName", paramType = "query", dataType = "string", required = true, value = "文件存储库名称"),

    })
    public Response upload(@RequestParam("file") MultipartFile file,
                         @RequestParam("bucketName") String bucketName) throws Exception{
        if (!minioClient.bucketExists(bucketName)) {
            minioClient.makeBucket(bucketName);
        }
        String prefixName = UUID.randomUUID().toString();
        StringBuilder sb = new StringBuilder();
        sb.append(prefixName).append(FileUtil.getFileSuffixName(file.getOriginalFilename()));
        minioClient.putObject(
                bucketName,
                sb.toString(),
                file.getInputStream(),
                MediaType.APPLICATION_OCTET_STREAM_VALUE);
        return Response.returnSuccess(sb.toString());
    }


    @GetMapping("/download")
    public void  download(@RequestParam("bucketName") String bucketName,
                          @RequestParam("fileKey") String fileKey,
                          HttpServletRequest request,
                          HttpServletResponse response) throws Exception{
        InputStream inputStream = minioClient.getObject(bucketName, fileKey);
        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        IOUtils.copy(inputStream,response.getOutputStream());
        response.flushBuffer();
    }
}
